package com.qms.repast.ui.presenter;

import android.app.Activity;
import android.text.TextUtils;

import com.orhanobut.logger.Logger;
import com.qms.repast.commons.Constants;
import com.qms.repast.entity.resbean.CityBean;
import com.qms.repast.entity.resbean.CityBean.BodyBean;
import com.qms.repast.module.UserModule;
import com.qms.repast.ui.base.BasePresenter;
import com.qms.repast.ui.view.ICityListView;
import com.qms.repast.weidgets.common.CharacterParser;
import com.qms.repast.weidgets.common.PinyinComparator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import io.reactivex.observers.DisposableObserver;

/**
 * @author 泅渡者
 * @date 2018/9/15 0015
 * @describe:
 */
public class CityListPresenter extends BasePresenter<ICityListView> {
	List<BodyBean> filterDateList;
	private CharacterParser characterParser;
	private PinyinComparator pinyinComparator;
	protected UserModule userModule;

	public CityListPresenter (Activity mContext, ICityListView mView) {
		super(mContext, mView);
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinComparator();
		userModule = new UserModule(mContext);
	}

	/**
	 * 根据输入内容改变数据集合
	 *
	 * @param inputStr
	 * @param sourceDateList
	 */
	public void filterDate (String inputStr, List<BodyBean> sourceDateList) {
		filterDateList = new ArrayList<>();
		if (TextUtils.isEmpty(inputStr)) {
			filterDateList = sourceDateList;
		} else {
			filterDateList.clear();
			if (sourceDateList != null && sourceDateList.size() > 0) {
				for (BodyBean sortModel : sourceDateList) {
					String name = sortModel.getCity();
					if (name.indexOf(inputStr) != -1 || characterParser.getSelling(name).startsWith(inputStr)) {
						filterDateList.add(sortModel);
					}
				}
			}

		}

		// 根据a-z进行排序
		if (filterDateList != null && filterDateList.size() > 0) {
			Collections.sort(filterDateList, pinyinComparator);
		}
		mView.updateData(filterDateList);
	}

	public void getCityList () {
		userModule.reqCityList(new DisposableObserver<CityBean>() {
			@Override
			public void onError (Throwable throwable) {
				Logger.e(throwable.getMessage());
			}

			@Override
			public void onComplete () {
				Logger.d("Request is End");
			}

			@Override
			public void onNext (CityBean cityBean) {
				if (Constants.SUCCESS==cityBean.getCode()) {
					List<BodyBean> findCityAllBeans = cityBean.getBody();
					if (findCityAllBeans != null && findCityAllBeans.size() > 0) {
						Collections.sort(findCityAllBeans, pinyinComparator);
					}
					mView.cityListData(findCityAllBeans);
				}
				Logger.d(cityBean.getBody());
			}
		});
	}
}
